﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.Infrastructure.Extentions;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;

namespace XSTDZ.ERP.WebApp.Controllers
{
     [NoAuthorizated]
    public class UserController : Controller
    {
         private readonly IUserService userServiceImpl = ServiceLocator.Instance.GetService<IUserService>();
         private readonly IOrgService orgServiceImpl = ServiceLocator.Instance.GetService<IOrgService>();	
        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }
        #region 查看详细
        [NoAuthorizated("UserDetail")]
        public ActionResult UserDetail(Guid id)
        {
            var genderlst = UserModel.GetUserGenderRadio();
            ViewBag.Gender = genderlst;
            var user = userServiceImpl.GetUser(id);
            user.Gender = user.Gender ?? "";
            if (!user.Password.IsEmpty())
            {
                user.Password = CryptographerLite.Decrypt(user.Password);
            }
            if (user.RoleIds != null && user.RoleIds.Count != 0)
            {
                var rids = "";
                user.RoleIds.Each(t => rids += t.ToString() + ";");
                ViewBag.StringRoleIds = rids;
            }
            genderlst.ForEach(g => g.Selected = (g.Value.ToString() == user.Gender.ToString()));
            return View(user);
        }
        #endregion
        #region 添加用户
          [NoAuthorizated("Add")]
        public ActionResult Add()
        {
            ViewBag.Gender = UserModel.GetUserGenderRadio();
            ViewBag.IsPiece = UserModel.GetUserIsPieceRadio();
            return View();
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(UserDto userDto)
        {
            var deptName = Request.Form["txtDeptName"];
            var userModel = new UserModel();
            /*
            userModel.InitUserRoles(userDto, Request.Form["RoleName_val"]);
           
            if (userDto.RoleIds == null || userDto.RoleIds.Count <= 0)
            {
                ModelState.AddModelError("RoleNameIds", "用户角色不能为空！");
            }
           */

            if (ModelState.IsValid)
            {
                if (!userServiceImpl.IsExists(userDto.AccountName))
                {
                    if (!userDto.DeptId.IsEmpty())
                    {
                        var dept = orgServiceImpl.GetDept(userDto.DeptId);
                        userDto.DeptId = dept.Id;
                        userDto.OrgId = dept.OrgId;
                    }
                    if (userDto.Birthday != null && userDto.Birthday.HasValue)
                    {
                        if (Convert.ToDateTime(userDto.Birthday.Value.ToString()) <= new DateTime(1900, 1, 1))
                        {
                            userDto.Birthday = new DateTime(1900, 1, 1);
                        }
                    }
                    if (!userDto.Password.IsEmpty())
                    {
                        userDto.Password = CryptographerLite.Encrypt(userDto.Password);
                    }
                    #region 先加入角色
                    IPermisstionService permissionServiceImpl = ServiceLocator.Instance.GetService<IPermisstionService>();
                    var roleDto = new RoleDto { Id = Guid.NewGuid(), Code = userDto.AccountName, Description = userDto.AccountName };

                    permissionServiceImpl.AddRole(roleDto);
                    #endregion
                    userDto.RoleIds = new HashSet<Guid>() { roleDto.Id };
                    this.userServiceImpl.AddUser(userDto);
                    ViewBag.PostState = 9;
                }
                else
                {
                    ModelState.Remove("AccountName");
                    ModelState.AddModelError("AccountName", "登陆名已存在！");
                }
            }
            #region 用户介面显示
            if (userDto.Dept == null)
            {
                userDto.Dept = new DeptDto();
            }
            userDto.Dept.Name = deptName;
            #endregion
            ViewBag.Gender = UserModel.GetUserGenderRadio();
            ViewBag.IsPiece = UserModel.GetUserIsPieceRadio();
            return View(userDto);
        }
        #endregion
        #region 修改用户
        [NoAuthorizated("Edit")]
        public ActionResult Edit(Guid userId)
        {
            var genderlst = UserModel.GetUserGenderRadio();

            ViewBag.Gender = genderlst;
            var user = this.userServiceImpl.GetUser(userId);
            user.Gender = user.Gender ?? "";
            if (!user.Password.IsEmpty())
            {
                user.Password = CryptographerLite.Decrypt(user.Password);
            }

            if (user.RoleIds != null && user.RoleIds.Count != 0)
            {
                var rids = "";
                user.RoleIds.Each(t => rids += t.ToString() + ";");
                ViewBag.StringRoleIds = rids;
            }

            var isPieceList = UserModel.GetUserIsPieceRadio();
            ViewBag.IsPiece = isPieceList;
            isPieceList.ForEach(t => { t.Selected = t.Value == user.IsPiece; });
            genderlst.ForEach(g => g.Selected = (g.Value.ToString() == user.Gender.ToString()));
            return View(user);
        }
        [HttpPost]
        [NoAuthorizated("Edit")]
        public ActionResult Edit(UserDto userDto)
        {
            var deptName = Request.Form["txtDeptName"];
            var userModel=new UserModel();
            userModel.InitUserRoles(userDto, Request.Form["RoleName_val"]);

            if (userDto.RoleIds == null || userDto.RoleIds.Count == 0)
            {
                userModel.InitUserRoles(userDto, Request.Form["RoleNameVal"]);
            }
            if (userDto.RoleIds == null || userDto.RoleIds.Count <= 0)
            {
                ModelState.AddModelError("RoleNameIds", "用户角色不能为空！");
            }

            if (ModelState.IsValid || (!ModelState.IsValid && userDto.RoleIds != null && userDto.RoleIds.Count>0))
            {
                userDto.UpdateID = UserModel.GetLoginUserId(this.HttpContext);
                userDto.UpdateDate = DateTime.Now;
                if (!userDto.DeptId.IsEmpty())
                {
                    var dept = orgServiceImpl.GetDept(userDto.DeptId);
                    userDto.DeptId = dept.Id;
                    userDto.OrgId = dept.OrgId;
                    deptName = dept.Name;
                }
                if (!userDto.Password.IsEmpty())
                {
                    userDto.Password = CryptographerLite.Encrypt(userDto.Password);
                }
                this.userServiceImpl.UpdateUser(userDto);
                ViewBag.PostState = 9;
            }
            #region 用户介面显示
            if (userDto.Dept == null)
            {
                userDto.Dept = new DeptDto();
            }
            userDto.Dept.Name = deptName;
            #endregion
            ViewBag.Gender = UserModel.GetUserGenderRadio();
            ViewBag.IsPiece = UserModel.GetUserIsPieceRadio();
            return View(userDto);
        }
        #endregion
        #region 修改密码
         
         public ActionResult ChangeUserPassword()
        {
            Guid userId = UserModel.GetLoginUserId(this.HttpContext);
            var user = userServiceImpl.GetUser(userId);
            if (!user.Password.IsEmpty())
            {
                user.Password = CryptographerLite.Decrypt(user.Password);
            }
            return View(user);
        }
         [HttpPost]
         [NoAuthorizated("ChangeUserPassword")]
         public ActionResult ChangeUserPassword(UserDto userDto)
         {
             var user = userServiceImpl.GetUser(userDto.Id);
             user.Password = CryptographerLite.Decrypt(user.Password);
             var orgPassword = Request.Form["OrgPassword"];
             var newPassword = Request.Form["NewPassword"];
             var confirmPassword = Request.Form["ComfirmPassword"];

             var userModel = new UserModel();
            var validateVal= userModel.ValidateUserPassword(user.Password,orgPassword, newPassword, confirmPassword);
            if (!string.IsNullOrEmpty(validateVal))
            {
                ModelState.AddModelError("", validateVal);
            }
            else
            {
                user.Password = newPassword;
                user.Password = CryptographerLite.Encrypt(user.Password);
                if (!userDto.Password.IsEmpty())
                {
                    userDto.Password = CryptographerLite.Encrypt(userDto.Password);
                }
                userServiceImpl.UpdateUser(user);
                ViewBag.Success = "更新成功！";
            }
            return View(user);
         }
        #endregion
        #region 删除操作
          [NoAuthorizated("Delete")]
        public ContentResult Delete(Guid userId)
        {
            this.userServiceImpl.DeleteUser(userId);
            return Content("ok");
        }
        #endregion
        #region 禁用用户操作
          [NoAuthorizated("DisableUser")]
        public ContentResult DisableUser(Guid userId,bool isEnable)
        {
            this.userServiceImpl.DisableUser(userId, isEnable);
            return Content("ok");
        }
        #endregion
        #region 返回用户列表
        [NoAuthorizated("GetAllUsers")]
        public ActionResult GetAllUsers()
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            var users = userServiceImpl.GetAllUser();
            if (users != null && users.Count() != 0)
            {
                var jsonResult = users.Select(u => new
                {
                    Key=u.Id,
                    LoginName = u.AccountName,
                    Name = u.Name,
                    OrgName = u.Org.Name,
                    DeptName = u.Dept.Name,
                    Gender = u.Gender == "1" ? "男" : "女",
                    Mobile = u.Mobile??"",
                    Birthday=u.Birthday.Value>DateTime.Parse("1900-01-01")?u.Birthday.Value.ToString("yyyy-MM-dd"):"",
                    Tel = u.Tel??"",
                    QQ = u.QQ??"",
                    IsEnable = "正常"
                });

               var target= Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
               target = "{\"Rows\":" + target + ",\"Total\":\"10\"}";
               return Content(target);
               
            }
            return View();
             */
            #endregion
            return Content(new BLLQuery().GetAllUsers(this.HttpContext));
        }

        [NoAuthorizated("GetAllUserList")]
        public ActionResult GetAllUserList()
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            var users = userServiceImpl.GetAllUser();
            if (users != null && users.Count() != 0)
            {
                var jsonResult = users.Select(u => new
                {
                    Key=u.Id,
                    LoginName = u.AccountName,
                    Name = u.Name,
                    OrgName = u.Org.Name,
                    DeptName = u.Dept.Name,
                    Gender = u.Gender == "1" ? "男" : "女",
                    Mobile = u.Mobile??"",
                    Birthday=u.Birthday.Value>DateTime.Parse("1900-01-01")?u.Birthday.Value.ToString("yyyy-MM-dd"):"",
                    Tel = u.Tel??"",
                    QQ = u.QQ??"",
                    IsEnable = "正常"
                });

               var target= Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
               target = "{\"Rows\":" + target + ",\"Total\":\"10\"}";
               return Content(target);
               
            }
            return View();
             */
            #endregion
            return Content(new BLLQuery().GetUserLists(this.HttpContext));
        } 
        #endregion
    }
}
